import { defineStore } from 'pinia';
import { reactive, ref } from 'vue';
import * as Utils from './utils';
import * as Api from '@/api/project/project';
import * as ApiTypes from '@/api/project/project.d';
import { LoginRes } from '@/api/user/user.d';
import type * as Types from './type';

const predefineColors = ['#FF0000', '#FF7F00', '#FFFF00' ,'#00FF00','#0000FF','#0000FF','#FF00FF','#FF3300','#FF9900','#99FF00','#00FFFF','#6600FF','#FF0066']

const useProjectDetailStore = defineStore('projectDetail', {
  // persist: true,
  persist: {
    key: 'projectinfo',
    storage: window.sessionStorage,
    // paths: ['form']
  },
  state: (): Types.ProjectDetailState => ({
    ready: true, //按钮准备状态（内容是否渲染完成）true为loading
    step: 1,
    taskId: null,
    form: reactive({
      basicSetting: reactive({
        name: '',
        department: '',
        label: '',
        target: '',
        uses: '',
        discardCode: [],
      }) as Types.ViewBasicSetting,
      annoSetting: reactive({
        defaultWindow: '',
        findings: false,
        diagnosis: false,
        showYay: false,
        showReport: false,
        imageLayout: '',
        seriesFcList: <number[]>[],
        seriesDataList: <Types.SeriesDataItem[]>[],
        lesionList: <string[]>[],
        lesionDataList: <Types.LesionDataList[]>[],
      }) as Types.ViewAnnoSetting,
      dataSetting: reactive({
        seriesList: [],
      }) as Types.ViewDataSetting,
      annoUserSetting: reactive({
        remark: '',
        crossNum: 2,
        annoUserList: <Types.AnnoUserItem[]>[],
      }) as Types.ViewAnnoUserSetting,
    }),
    apiForm: reactive({
      basicSetting: reactive({}) as Types.BasicSetting,
      annoSetting: reactive({}) as Types.AnnoSetting,
      dataSetting: reactive({
        seriesList: []
      }) as Types.DataSetting,
      annoUserSetting: reactive({}) as Types.AnnoUserSetting,
    }),
    commonList: {
      departments: [],
      discardReasons: [],
      imageLayouts: [],
      imageTransferModes: [],
      lesionBizTypes: [],
      taskLabels: [],
      taskTargets: [],
      taskUses: [],
      windows: [],
    } as ApiTypes.CommonConfigResponse,
    compList: [] as ApiTypes.CompConfigItem[],
    compTotal: 0,
    toolList: [] as ApiTypes.ToolConfigItem[],
    lesionList: [] as ApiTypes.LesionConfigItem[],
    userList: [] as LoginRes[],
    userTotal: 0,
    companyList: [] as ApiTypes.CompanyConfigItem[],
    // compAlertList: [] as Types.SeriesDataItem[],
  }),
  getters: {
    getStepForm():
      | {
          basicSetting: Types.ViewBasicSetting;
          annoSetting: Types.ViewAnnoSetting;
        }
      | Types.ViewDataSetting
      | Types.ViewAnnoUserSetting {
      const resEnum = {
        1: reactive({
          basicSetting: this.form.basicSetting,
          annoSetting: this.form.annoSetting,
        }),
        2: this.form.dataSetting,
        3: this.form.annoUserSetting,
      };
      return resEnum[this.step];
    },
  },
  actions: {
    async initData() {
      try {
        // 获取下拉配置
        const commonRes = await Api.getCommonConfig({});
        this.commonList = commonRes.data;
        // 获取病灶数据
        const lesionRes = await Api.getLesionConfig(
          Object.assign({}, { page: 1, pageSize: 100000 })
        );
        this.lesionList = lesionRes.data.list;
        this.getCompData(1);
        // 获取工具配置
        const toolRes = await Api.getToolConfig(
          Object.assign({}, { page: 1, pageSize: 100000 })
        );
        this.toolList = toolRes.data.list;
      } catch (error) {
        console.log('初始化接口异常', error);
      }
    },
    // 获取征象组件数据根据分页获取
    async getCompData(page: number) {
      try {
        // 获取组件配置
        const compRes = await Api.getComponentConfig(
          Object.assign({}, { page, pageSize: 10 })
        );
        this.compList = compRes.data.list;
        this.compTotal = compRes.data.total;
      } catch (error) {
        console.log('初始化组件配置接口异常', error);
      }
    },
    // 获取已添加组件弹窗数据
    async getCompDialog(ids: number[], flag = false, value?: string) {
      try {
        const compRes = await Api.getComponentConfig(
          Object.assign({}, { ids, page: 1, pageSize: 10 })
        );
        if (flag) {
          this.form.annoSetting.seriesDataList = compRes.data.list.map(
            (item) => {
              return {
                ...item,
                required: false,
              };
            }
          );
        } else {
          // 通过病灶value查找当前项
          const currentItem = this.form.annoSetting.lesionDataList.find(
            (item) => item.lesionValue === value
          );
          if (currentItem) {
            currentItem.imageDataList = compRes.data.list.map((item) => {
              return {
                ...item,
                required: false,
              };
            });
          }
        }
      } catch (error) {
        console.log('查询组件配置接口异常', error);
      }
    },
    // 数据回填查询组件数据
    async getCompDataDialog(
      data: ApiTypes.FcItem[],
      flag = false,
      list?: {
        required: boolean;
        createTime: number;
        updateTime: number;
        code: string;
        data: string;
        editable: boolean;
        id: number;
        name: string;
        parameter: string;
        type: string;
      }[]
    ) {
      try {
        const ids = data.map((item) => item.fcId);
        const compRes = await Api.getComponentConfig(
          Object.assign({}, { ids, page: 1, pageSize: 10 })
        );
        if (flag) {
          const tempArr: Types.SeriesDataItem[] = [];
          data.map((item) => {
            const current = compRes.data.list.find(t => t.id === item.fcId)
            current && (tempArr.push({
              ...current,
              required: item.required,
            }))
          });
          this.form.annoSetting.seriesDataList = tempArr;
          // @ts-ignore
          // this.form.annoSetting.seriesDataList = data.map((t) => {
          //   const fcItem = compRes.data.list.find(item => item.id === t.fcId)
          //   return {
          //     ...fcItem,
          //     required: t.required,
          //   };
          // });
        } else {
          data.map((t) => {
            compRes.data.list.map((item) => {
              if (item.id === t.fcId) {
                list?.push({
                  ...item,
                  required: t.required,
                });
              }
            });
          });
        }
      } catch (error) {
        console.log('查询组件配置接口异常', error);
      }
    },
    // 获取任务详情
    async getProjectDetail(id: number) {
      this.ready = true
      try {
        const detail = await Api.getProjectDetail(id);
        console.log(detail.data, '详情');
        const { taskInfo, dataInfo, annoInfo, annoUserInfo } =
          detail?.data?.data;
        this.apiForm = {
          basicSetting: taskInfo,
          annoSetting: annoInfo,
          dataSetting: dataInfo,
          annoUserSetting: annoUserInfo,
        };
        this.form = Utils.transformApiForm(
          this.form,
          this.apiForm,
          this.lesionList,
          this.getCompDataDialog
        );
        setTimeout(() => {
          this.ready = false;
        }, 1000);
      } catch (error) {
        console.log('获取任务详情接口异常', error);
      }
    },
    // 获取标注人员数据
    async getUserList() {
      try {
        const userRes = await Api.getUserData(
          Object.assign({}, { status: 1, pageSize: 1000000 })
        );
        this.userList = userRes.data.list;
        this.userTotal = userRes.data.total;
      } catch (error) {
        console.log('获取用户数据接口异常', error);
      }
    },
    // 获取组织机构数据
    async getCompanyData() {
      try {
        const companyRes = await Api.getCompanyConfig(
          Object.assign({}, { status: 1 })
        );
        this.companyList = companyRes.data;
      } catch (error) {
        console.log('获取组织机构数据接口异常', error);
      }
    },
    // 任务名称查重
    async existedName(id?: number): Promise<boolean> {
      const result = await Api.existedProjectName({
        id,
        name: this.form.basicSetting.name,
      });
      return result.data.result;
    },
    // 保存数据
    async saveData(flag = false, id?: number | undefined) {
      try {
        Utils.transformForm(this.form, this.apiForm, this.lesionList);
        console.log(this.apiForm, '请求千参数');
        let res: any = {};
        if (flag) {
          //create
          res = await Api.saveTaskData(this.apiForm);
        } else {
          res = await Api.updateTaskData({ ...this.apiForm, id });
        }
        if (res.code === 200) {
          //todo 保存新建的task id
          this.taskId = res.data?.id;
          this.step = 4;
        }
      } catch (error) {
        console.log('保存数据接口异常', error);
      }
    },
    // 监听表单字段，用来提交时只传修改字段 todo
    watchFormData(formData: string) {
      try {
        if (formData === '') {
          throw Error('参数不可为空字符串');
        }
        if (formData.indexOf('.') === -1) {
          throw Error('参数不符合表单路径格式, 请传入带.的表单路径');
        }
        if (formData.indexOf('.') !== -1) {
          const formUrls = formData.split('.');
          console.log(formUrls, '监听表单数据');
          console.log(this.form[formUrls[0]][formUrls[1]] , "this.form[formUrls[0]][formUrls[1]] ");
        }
      } catch (error) {
        console.log('表单监听逻辑异常', error);
      }
    },
    // 表单上一步下一步按键
    handleStepClick(flag = false) {
      flag && this.step++;
      !flag && this.step--;
    },
    // 根据标注类型处理标注类型表格数据
    getFormLeisonDataList() {
      const lesionList = [] as ApiTypes.LesionConfigItem[];
      this.lesionList.map((item) => {
        if (item.childs && item.childs.length !== 0) {
          item.childs.map((t) => {
            lesionList.push(t);
          });
        } else {
          lesionList.push(item);
        }
      });
      const tempArr = lesionList.filter((item) =>
        this.form.annoSetting.lesionList.includes(item.value)
      );
      const changeTempArr = tempArr.map((item,index) => {
        return {
          lesionValue: item.value,
          name: item.name,
          color: item.color || predefineColors[index] || '#fff',
          toolValueList: [],
          imageFcList: [],
          imageList: [],
          imageDataList: [],
        };
      });
      // 病灶数据插入or删除
      const lesionVal = this.form.annoSetting.lesionDataList.map(
        (item) => item.lesionValue
      );
      changeTempArr.map((item) => {
        if (!lesionVal.includes(item.lesionValue)) {
          this.form.annoSetting.lesionDataList.push(item);//插入
        }
      });
      const len = this.form.annoSetting.lesionDataList.length
      const selectedCodeArr = changeTempArr.map(item => item.lesionValue);
      for(let i = len -1; i >= 0; i--){
        const one = this.form.annoSetting.lesionDataList[i]
        if(!selectedCodeArr.includes(one.lesionValue)){
          this.form.annoSetting.lesionDataList.splice(i, 1)//删除
        }
      }
    },
    // 根据影响布局切换重置标注类型及标注类型表格
    clearLesionList() {
      this.form.annoSetting.lesionList = [];
      this.form.annoSetting.lesionDataList = [];
    },
    // 重置表单
    resetFields() {
      this.form = {
        basicSetting: reactive({
          name: '',
          department: '',
          label: '',
          target: '',
          uses: '',
          discardCode: [],
        }) as Types.ViewBasicSetting,
        annoSetting: reactive({
          defaultWindow: '',
          findings: false,
          diagnosis: false,
          showYay: false,
          showReport: false,
          imageLayout: '',
          seriesFcList: <number[]>[],
          seriesDataList: <Types.SeriesDataItem[]>[],
          lesionList: <string[]>[],
          lesionDataList: <Types.LesionDataList[]>[],
        }) as Types.ViewAnnoSetting,
        dataSetting: reactive({
          seriesList: [],
        }) as Types.ViewDataSetting,
        annoUserSetting: reactive({}) as Types.ViewAnnoUserSetting,
      };
      this.apiForm = {
        basicSetting: reactive({}) as Types.BasicSetting,
        annoSetting: reactive({}) as Types.AnnoSetting,
        dataSetting: reactive({
          seriesList: [],
        }) as Types.DataSetting,
        annoUserSetting: reactive({}) as Types.AnnoUserSetting,
      };
      // this.compAlertList = [];
      this.step = 1;
      this.ready = false;
    },
    // 根据标注组件弹窗数据排序
    sortAlertTableData(
      data: Types.SeriesDataItem[],
      flag = false,
      value?: string
    ) {
      flag && (this.form.annoSetting.seriesDataList = data);
      if (!flag) {
        const currentItem = this.form.annoSetting.lesionDataList.find(
          (item) => item.lesionValue === value
        );
        currentItem && (currentItem.imageDataList = data);
      }
    },
    // 清空小征象弹窗数据
    clearAlertTableData(value?: string) {
      // this.compAlertList = [];
      const currentItem = this.form.annoSetting.lesionDataList.find(
        (item) => item.lesionValue === value
      );
      currentItem && (currentItem.imageDataList = []);
    },
    // 下拉全选分页组件设置数据
    setSelectCheckAll(flag = false, value?: string) {
      const tempArr = this.compList.map((item) => item.id);
      if (flag) {
        // 大征象
        tempArr.map((item) => {
          if (!this.form.annoSetting.seriesFcList.includes(item)) {
            this.form.annoSetting.seriesFcList.push(item);
          }
        });
        this.getCompDialog(this.form.annoSetting.seriesFcList, true);
      } else {
        // 通过病灶value查找当前项
        const currentItem = this.form.annoSetting.lesionDataList.find(
          (item) => item.lesionValue === value
        );
        // 小征象
        tempArr.map((item) => {
          if (currentItem && !currentItem.imageList.includes(item)) {
            currentItem.imageList.push(item);
          }
        });
        currentItem && this.getCompDialog(currentItem.imageList, false, value);
      }
    },
    // 下拉全选清空
    clearSelectCheckAll(flag = false, value?: string) {
      const tempArr = this.compList.map((item) => item.id);
      if (flag) {
        // 大征象
        tempArr.map((item) => {
          if (this.form.annoSetting.seriesFcList.includes(item)) {
            this.form.annoSetting.seriesFcList =
              this.form.annoSetting.seriesFcList.filter((t) => t !== item);
          }
        });
      } else {
        // 小征象
        // 通过病灶value查找当前项
        const currentItem = this.form.annoSetting.lesionDataList.find(
          (item) => item.lesionValue === value
        );
        // 小征象
        tempArr.map((item) => {
          if (currentItem && !currentItem.imageList.includes(item)) {
            currentItem.imageList = currentItem.imageList.filter(
              (t) => t !== item
            );
          }
        });
      }
    },
    // 征象组件弹窗删除操作
    delCompAlertData(data: Types.SeriesDataItem, flag = false, value?: string) {
      if (flag) {
        // 大征象
        if (this.form.annoSetting.seriesFcList.includes(data.id)) {
          this.form.annoSetting.seriesFcList =
            this.form.annoSetting.seriesFcList.filter(
              (item) => item !== data.id
            );
          this.form.annoSetting.seriesDataList =
            this.form.annoSetting.seriesDataList.filter(
              (item) => item.id !== data.id
            );
        }
      } else {
        // 通过病灶value查找当前项
        const currentItem = this.form.annoSetting.lesionDataList.find(
          (item) => item.lesionValue === value
        );
        // 小征象
        if (currentItem) {
          currentItem.imageList = currentItem.imageList.filter(
            (item) => item !== data.id
          );
          currentItem.imageDataList = currentItem.imageDataList.filter(
            (item) => item.id !== data.id
          );
        }
      }
    },
    // 病灶表格删除操作
    delLesionData(value: string) {
      this.form.annoSetting.lesionList =
        this.form.annoSetting.lesionList.filter((item) => item != value);
      this.form.annoSetting.lesionDataList =
        this.form.annoSetting.lesionDataList.filter(
          (item) => item.lesionValue !== value
        );
    },
    // 病灶表格病灶设置互斥
    changeBizType(value: number, lesionVal: string) {
      this.form.annoSetting.lesionDataList =
        this.form.annoSetting.lesionDataList.map((item) => {
          delete item.bizType;
          if (lesionVal === item.lesionValue) {
            item.bizType = value;
          }
          return item;
        });
    },
    // 增加标注人数
    addAnnoUserList() {
      this.form.annoUserSetting.annoUserList.push({
        companyId: null as unknown as number,
        userIdList: [],
        userList: [],
      });
    },
    // 清空标注人数
    clearAnnoUserList() {
      this.form.annoUserSetting.annoUserList = [];
    },
    // 删除标注人数
    delAnnoUserList(i: number) {
      this.form.annoUserSetting.annoUserList =
        this.form.annoUserSetting.annoUserList.filter(
          (item, index) => index !== i
        );
    },
    // 根据当前组织机构获取当前用户
    async getUserDataList(companyId: number) {
      try {
        const userRes = await Api.getUserData(
          Object.assign({}, { companyId, status: 1, pageSize: 1000000 })
        );
        const currentItem = this.form.annoUserSetting.annoUserList.find(
          (item) => item?.companyId === companyId
        );
        if (currentItem) {
          // currentItem.userList.splice(0)
          currentItem.userList = userRes.data.list;
          currentItem.userIdList = []; //清空选中人员
        }
      } catch (error) {
        console.log('查询用户数据接口异常', error);
      }
    },
  },
});

export default useProjectDetailStore;
